package ngram.reader;

import exceptions.NegativeNumberException;
import exceptions.NegativeNumberOrZeroException;
import java.io.BufferedReader;
import java.io.IOException;

/**
 *
 * @author g1wshimu
 */
public class TextFileReader implements NGramFileReader {

    private final BufferedReader READER;
    public static final String TAB = "\u0009";
    /**
     * The total number of lines read so far.
     */
    private int lineCount = 0;
    
    private String[] tokens;

    public TextFileReader(BufferedReader reader) {
        this.READER = reader;
    }

    public int getLineCount() {
        return lineCount;
    }

    @Override
    public String readNGram() throws IOException {
        String line = READER.readLine();
        if (line == null) {
            return null;
        }
        lineCount++;

        line = line.trim();
        if (line.isEmpty()) {
            return "";
        }

        this.tokens = line.split(TAB);

        // There should be between 1 to 5 tokens
        assert (tokens.length < 6) && (tokens.length > 0);

        // Version 1: ngram TAB year TAB match_count TAB page_count 
        //            TAB volume_count NEWLINE
        // Version 2: ngram TAB year TAB match_count TAB volume_count NEWLINE
        return tokens[0].trim();
    }

    @Override
    public int readYear() throws IOException, NegativeNumberException {
        int year = Integer.parseInt(tokens[1]);
        NegativeNumberException.validate("year", year);
        return year;
    }

    @Override
    public long readVolumeCount() throws IOException, NegativeNumberException {
        // We keep only the volume_count (i.e. ignores the page lineCount 
        // if it was version 1)
        long volumeCount = Long.parseLong(tokens[tokens.length - 1]);
        NegativeNumberException.validate("Volume count", volumeCount);
        return volumeCount;
    }

    @Override
    public long readMatchCount() throws IOException, NegativeNumberException {
        long matchCount = Long.parseLong(tokens[2]);
        NegativeNumberException.validate("Match count", matchCount);
        return matchCount;
    }

    @Override
    public int readHeader() throws IOException, NegativeNumberOrZeroException {
        throw new UnsupportedOperationException("Not supported yet.");
    }
}
